import { LOCAL_STORE } from '@/utils/code'

const TIME_CODE = {
    /** @param 操作成功 */
    SUCCEED: 200,
    /** @param 找不到缓存 */
    NOT_FOUND: 404,
    /** @param 缓存过期 */
    PAST_DUE: 401,
    /** @param 操作失败 */
    FAIL: 1
}

const PAST_TIME = (key, name, expired) => {
    let TIME_LEAN = null
    switch (key) {
        case 'SET':
            try {
                localStorage.setItem(`${name}_EXPIRED`, `${Date.now() + 1000 * 60 * expired}`);
                TIME_LEAN = TIME_CODE.SUCCEED
            } catch (error) {
                TIME_LEAN = TIME_CODE.FAIL
            }
            break;
        case 'GET':
            try {
                const value = localStorage.getItem(`${name}_EXPIRED`);
                if (value > Date.now() || !value) {
                    TIME_LEAN = TIME_CODE.SUCCEED
                } else {
                    try {
                        localStorage.removeItem(name)
                        localStorage.removeItem(`${name}_EXPIRED`)
                    } catch (error) {
                        TIME_LEAN = TIME_CODE.NOT_FOUND
                    }
                }
            } catch (error) {
                TIME_LEAN = TIME_CODE.NOT_FOUND
            }
            break;
    }
    return TIME_LEAN;
}

export default ((param) => {
    LOCAL_STORE().map(item => {
        param[item] = {
            setItem: (value, time = null) => {
                return new Promise((reslove) => {
                    if (time && PAST_TIME('SET', item, time) != TIME_CODE.SUCCEED) {
                        return reslove(false)
                    }
                    localStorage.setItem(item, JSON.stringify(value));
                })
            },
            getItem: () => {
                return new Promise((reslove) => {
                    if (PAST_TIME('GET', item) == TIME_CODE.PAST_DUE) {
                        return reslove(null)
                    }
                    reslove(JSON.parse(localStorage.getItem(item)))
                })
            },
            removeItem: () => {
                if (PAST_TIME('GET', item) == TIME_CODE.PAST_DUE) {
                    try {
                        localStorage.removeItem(name)
                        localStorage.removeItem(`${name}_EXPIRED`)
                        return TIME_CODE.PAST_DUE
                    } catch (error) {
                        return error
                    }
                }

                try {
                    localStorage.removeItem(item)
                } catch (error) {
                    return error
                }
            }
        }
    })
    return param
})({})